﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.Common;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using NLog;
namespace Casamiel.API.Application.Services
{
    /// <summary>
    /// Stock service.
    /// </summary>
    public class StockService : IStockService
    {
        private readonly NLog.ILogger _stocklogger = LogManager.GetLogger("StockService");
        private readonly Queue<StockPush> queue = new Queue<StockPush>();
        private static object obj = new object();
        private long delaytime = 0;
        private long unpushtime = 0;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly string SmsSignName = "";
        private readonly bool _checkPushStock = false;
        private readonly IIcApiService _icApiService;
        private readonly IMediator _mediator;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Application.Services.StockService"/> class.
        /// </summary>
        /// <param name="httpClientFactory">Http client factory.</param>
        /// <param name="settings">Settings.</param>
        /// <param name="casameilSettings">Casameil settings.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="mediator">Mediator.</param>
        public StockService(IHttpClientFactory httpClientFactory, IOptions<AliyunSettings> settings, IOptions<CasamielSettings> casameilSettings,
                           IIcApiService iicApiService, IMediator mediator)
        {
            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            if (casameilSettings == null) {
                throw new ArgumentNullException(nameof(casameilSettings));
            }

            SmsSignName = settings.Value.SmsSignName;//SmsSignName
            _checkPushStock = casameilSettings.Value.CheckPushStock;
            _icApiService = iicApiService;
            _httpClientFactory = httpClientFactory;
            _mediator = mediator;
            // Thread t3=new   Thread(async () => ;)
            Thread t1 = new Thread(async () => await Dequeue().ConfigureAwait(false)) {
                IsBackground = true
            };
            t1.Start();

            //
            //Thread t2 = new Thread(new ThreadStart(UpdateStock))
            Thread t2 = new Thread(async () => await UpdateStock().ConfigureAwait(false)) {
                IsBackground = true
            };
            t2.Start();
        }
        /// <summary>
        /// Adds the queue.
        /// </summary>
        /// <param name="info">Info.</param>
        public void AddQueue(StockPush info)
        {
            if (info != null) {
                if (SmsSignName == "可莎蜜兒") {
                    info.Source = 0;
                } else {
                    info.Source = 1;
                }
                lock (obj) {
                    delaytime = 0;
                    unpushtime = 0;
                }
                queue.Enqueue(info);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public long GetUnpushtime()
        {
            return unpushtime;
        }

        private void DoUpdateStock()
        {
            try {
                var url = "";
                if (SmsSignName == "可莎蜜兒") {
                    url = "https://api.casamiel.cn";

                }
                if (SmsSignName.Contains("皇冠", StringComparison.OrdinalIgnoreCase)) {


                    url = "https://api.hgsp.cn";
                    //return;
                }
                if (SmsSignName == "东哥食品") {
                    url = "https://api.donco.com.cn";
                }
                lock (obj) {
                    delaytime = 0;
                }
                using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{url}/api/v2/MeiTuan/kucun2")) {
                    // requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("");
                    var response = client.SendAsync(requestMessage).GetAwaiter().GetResult();
                    if (response.IsSuccessStatusCode) {
                        var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                        _stocklogger.Trace($"{result}");
                    } else {
                        _stocklogger.Error($"UpdateStock:{ response.StatusCode}");
                    }
                }


            } catch (HttpRequestException ex) {
                _stocklogger.Error("stockPush:" + ex.StackTrace);
            }
        }
        /// <summary>
        /// Updates the stock.
        /// </summary>
        public async Task<bool> UpdateStock()
        {
            while (true) {
                if (_checkPushStock) {
                    if (DateTime.Now.Hour >= 6 && DateTime.Now.Hour < 22) {
                        if (unpushtime > 300000) {
                            var url = "";
                            if (SmsSignName == "可莎蜜兒") {
                                url = "https://api.casamiel.cn";
                            }
                            if (SmsSignName.Contains("皇冠", StringComparison.OrdinalIgnoreCase)) {
                                url = "https://api.hgsp.cn";
                            }
                            if (SmsSignName == "东哥食品") {
                                url = "https://api.donco.com.cn";
                            }
                            var zmodel = new Zmodel();
                            //Task.Run(async () =>
                            //{
                            zmodel = await _icApiService.Stockpushplan(new Models.ICModels.StockpushPlanReq { Pushurl = $"{url}/api/v1/Stock/UpdateStock", Start = true })
                            .ConfigureAwait(false);

                            //  }).GetAwaiter().GetResult();

                            if (zmodel.code == 0) {
                                lock (obj) {
                                    unpushtime = 0;

                                }
                            }
                        }
                        if (delaytime > 600_000) {
                            _stocklogger.Error($"{delaytime}毫秒没推送了S");
                            DoUpdateStock();

                        } else {
                            Thread.Sleep(300);
                        }
                    } else if (DateTime.Now.Hour < 6 || DateTime.Now.Hour > 22) {
                        if (unpushtime > 1800000) {
                            var url = "";
                            if (SmsSignName == "可莎蜜兒") {
                                url = "https://api.casamiel.cn";
                            }
                            if (SmsSignName.Contains("皇冠", StringComparison.OrdinalIgnoreCase)) {
                                url = "https://api.hgsp.cn";
                            }
                            if (SmsSignName == "东哥食品") {
                                url = "https://api.donco.com.cn";
                            }
                            var zmodel = new Zmodel();
                            //Task.Run(async () =>
                            //{
                            zmodel = await _icApiService.Stockpushplan(new Models.ICModels.StockpushPlanReq { Pushurl = $"{url}/api/v1/Stock/UpdateStock", Start = true }).ConfigureAwait(false);
                            //}).GetAwaiter().GetResult();
                            if (zmodel.code == 0) {
                                lock (obj) {
                                    unpushtime = 0;
                                }
                            }
                        }
                        if (delaytime > 6000000) {
                            DoUpdateStock();
                        }

                    }

                } else {
                    lock (obj) {
                        delaytime = 0;
                        unpushtime = 0;
                    }

                }
                Thread.Sleep(1000);
            }
        }
        /// <summary>
        /// Dododod this instance.
        /// </summary>
        public Task Dequeue()
        {
            while (true) {
                if (queue.Count > 0) {
                    var data = queue.Dequeue();
                    if (SmsSignName == "东哥食品") {
                       
                    var command = new UpdateStockCommand(data);
                        _mediator.Publish(command).Wait();
                        lock (obj) {
                            delaytime = 0;
                            unpushtime = 0;
                        }
                    } else {
                        try {
                            Parallel.Invoke(() => {
                                var command = new UpdateStockCommand(data);
                                _mediator.Publish(command).Wait();
                            }, () => {
                                try {
                                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/StockPush") {
                                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                                    };
                                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                                    HttpResponseMessage response = new HttpResponseMessage();
                                    Task.Run(async () => {
                                        response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                                        if (response.IsSuccessStatusCode) {
                                            var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                            _stocklogger.Trace($"{result}");
                                            lock (obj) {
                                                delaytime = 0;
                                                unpushtime = 0;
                                            }
                                        } else {
                                            _stocklogger.Error($"{data},{ response.StatusCode}");
                                        }
                                    }).Wait();

                                } catch (AggregateException ex) {
                                    _stocklogger.Error("stockPush:" + ex.StackTrace);
                                    queue.Enqueue(data);
                                }
                            });
                        } catch (AggregateException ex) {
                            _stocklogger.Error(ex.Message);
                            foreach (var exinfo in ex.InnerExceptions) {
                                _stocklogger.Error(exinfo.StackTrace);
                            }

                        }

                        //if (SmsSignName.Contains("可莎蜜兒"))
                        //{

                    }
                    // }
                } else {
                    lock (obj) {
                        delaytime += 300;
                        unpushtime += 300;
                    }

                }
                Thread.Sleep(300);
            }

        }
    }
}
